
#!/usr/bin/env python3
"""
头条热门原创图文推送助手 - 启动脚本
支持一键启动后端服务和定时任务
"""

import os
import sys
import subprocess
import time
from pathlib import Path

def check_python_version():
    """检查Python版本"""
    if sys.version_info < (3, 8):
        print("❌ 需要 Python 3.8 或更高版本")
        sys.exit(1)
    print("✅ Python 版本检查通过")

def check_dependencies():
    """检查依赖包"""
    try:
        import fastapi
        import sqlalchemy
        import uvicorn
        print("✅ 依赖包检查通过")
    except ImportError as e:
        print(f"❌ 缺少依赖: {e}")
        print("正在安装依赖...")
        subprocess.run([sys.executable, "-m", "pip", "install", "-r", "backend/requirements.txt"])
        print("✅ 依赖安装完成")

def setup_database():
    """初始化数据库"""
    try:
        from backend.database.database import engine
        from backend.models.article import Base
        Base.metadata.create_all(bind=engine)
        print("✅ 数据库初始化完成")
    except Exception as e:
        print(f"❌ 数据库初始化失败: {e}")

def start_services():
    """启动服务"""
    print("\n🚀 启动头条热门原创图文推送助手...")
    
    # 确保日志目录存在
    os.makedirs("logs", exist_ok=True)
    
    # 启动定时任务（后台进程）
    print("📅 启动定时任务...")
    scheduler_process = subprocess.Popen([
        sys.executable, "backend/scheduler.py"
    ], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    
    time.sleep(2)
    
    # 启动Web服务
    print("🌐 启动Web服务...")
    print("访问地址: http://localhost:8000")
    print("API文档: http://localhost:8000/docs")
    
    try:
        subprocess.run([
            sys.executable, "-m", "uvicorn", 
            "backend.app.main:app",
            "--host", "0.0.0.0",
            "--port", "8000",
            "--reload"
        ])
    except KeyboardInterrupt:
        print("\n⏹️  正在停止服务...")
        scheduler_process.terminate()
        print("✅ 服务已停止")

def main():
    """主函数"""
    print("🔧 头条热门原创图文推送助手 - 初始化检查")
    print("=" * 50)
    
    check_python_version()
    check_dependencies()
    setup_database()
    
    print("\n" + "=" * 50)
    start_services()

if __name__ == "__main__":
    main()
